package com.jsm.twentyfour.service;

import com.github.pagehelper.PageHelper;
import com.jsm.twentyfour.domain.Account;
import com.jsm.twentyfour.domain.AccountExample;
import com.jsm.twentyfour.domain.Score;
import com.jsm.twentyfour.dto.AccountDTO;
import com.jsm.twentyfour.mapper.AccountMapper;
import com.jsm.twentyfour.mapper.BaseMapper;
import com.jsm.twentyfour.transfer.AccountTransfer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * create by jsm on 2019/1/23
 */
@Service
public class AccountService extends BaseService <Account, AccountDTO, AccountExample> {
    @Resource
    private AccountMapper accountMapper;
    @Resource

    private ScoreService scoreService;

    @Override
    public BaseMapper <Account, AccountExample> mapper() {
        return accountMapper;
    }

    @Override
    public Class <AccountDTO> getDTOClass() {
        return AccountDTO.class;
    }

    @Override
    public AccountDTO transfer(Account account) {
        return AccountTransfer.transfer(account);
    }

    @Transactional
    public AccountDTO login(Account account) {
        AccountDTO accountDTO = getByOpenId(account.getOpenId());
        if (accountDTO == null) {
            accountDTO = insertSelective(account);
            scoreService.insertSelective(Score.builder().score(0).userId(accountDTO.getId()).build());
            return accountDTO;
        } else {
            account.setId(accountDTO.getId());
            updateSelective(account);
            return AccountTransfer.transfer(account);
        }
    }

    public AccountDTO getByOpenId(String openId) {
        AccountExample accountExample = new AccountExample();
        accountExample.createCriteria().andOpenIdEqualTo(openId);
        return getByExample(accountExample);
    }
}
